package com.hd.contentmonitor.service;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;

import com.hd.contentmonitor.jdbc.JDBCConnection;

public class ContentChangeDisplayer {
	
	
	public ContentChangeDisplayer(){
		
	}
	
	public static void main(String args[]){
		System.out.println("args length..."+args.length);
		
		if(args.length >2 ){
			System.out.println("Max argument can only be two. Provide only the date range");
		}
		ContentChangeDisplayer ccd = new ContentChangeDisplayer();
		if(args[0] != null && args[1] == null){
			displayChangedContentInCSV(args[0]);
		}else if(args[0] != null && args[1] != null){
			displayChangedContentInCSV(args[0],args[1]);
		}
	}
	
	
	private static void displayChangedContentInCSV(String url,String date){
		System.out.println("under two args..");
		try{
			Connection connection = JDBCConnection.connect();
	        String source2="";
	        
	        ResultSet rs = JDBCConnection.executeQuery("SELECT DiffContent,DATETIME FROM sitemonitor.sitemonitordiff WHERE URL='"+url+"' and DATETIME <= STR_TO_DATE('"+date+"', '%Y-%m-%d') ");
	        FileOutputStream fileout = new FileOutputStream(new File("D://changecontent.csv"));
	        while(rs.next()){
		       	 source2=rs.getString(1);
		       	 String datetime=rs.getString(2);
		       	 
		       	 System.out.println("source..."+source2);
		       	 System.out.println("datetime..."+datetime);
		       	 fileout.write(("\nDATE,"+datetime+"\n").getBytes());
			     fileout.write(source2.getBytes());
			     fileout.flush();
	        }
	        fileout.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	private static void displayChangedContentInCSV(String url){
		try{
			Connection connection = JDBCConnection.connect();
	        String source2="";
	        
	        ResultSet rs = JDBCConnection.executeQuery("SELECT DiffContent FROM sitemonitor.sitemonitordiff WHERE URL='"+url+"' ORDER BY DATETIME DESC ");
	        if(rs.next()){
		       	 source2=rs.getString(1);
		       	 FileOutputStream fileout = new FileOutputStream(new File("D://changecontent.csv"));
			     fileout.write(source2.getBytes());
			     fileout.close();
	        }
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
